<template>
  <div
    ref="container"
    :style="{height:height,width:width}"
    style="overflow: hidden"
  />
</template>

<script lang="ts" setup>
import { onBeforeUnmount, onMounted, shallowRef, toRefs, watch } from 'vue'
import type { PropType } from 'vue'
import * as echarts from 'echarts'
import { IEchartsData } from '@/model/echarts/echartsInter'

const container = shallowRef<InstanceType<typeof HTMLElement>>()
const chart = shallowRef()
const prop = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '350px'
  },
  chartData: {
    type: Object as PropType<IEchartsData>,
    required: true
  },
  type: {
    type: String,
    required: true
  },
  num: {
    type: String,
    required: true
  }
})
const { width, height, chartData, type, num } = toRefs(prop)

// 初始化echarts
const initChart = () => {
  chart.value = echarts.init(container.value!)
  chart.value.showLoading({
    text: '加载中...',
    color: '#37C1F8',
    textColor: '#fff',
    maskColor: 'rgba(5, 44, 71, 0)',
    zlevel: 0
  })
}
const setOption = (chartData:IEchartsData) => {
  import('./' + type.value + 's/' + num.value).then(res => {
    chart.value.clear()
    chart.value.hideLoading()
    chart.value.setOption(res.Chart(chartData))
  })
}
const chartResizeFun = () => {
  chart.value.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', chartResizeFun, true)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', chartResizeFun, true)
  if (!chart.value) return
  chart.value.dispose()
  chart.value = null
})
watch(chartData, (value) => {
  setOption(chartData.value)
}, { immediate: true, deep: true })
</script>
